package com.itheima.health.service.impl;

import com.itheima.health.common.MessageConst;
import com.itheima.health.dao.OrderDao;
import com.itheima.health.dao.OrderSettingDao;
import com.itheima.health.dao.SetMealDao;
import com.itheima.health.dto.OrderDto;
import com.itheima.health.exception.BusinessRuntimeException;
import com.itheima.health.pojo.Order;
import com.itheima.health.pojo.OrderSetting;
import com.itheima.health.service.OrderService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.Objects;

/**
 * 预约ServiceImpl
 */
@Service
@Slf4j
public class OrderServiceImpl implements OrderService {
    @Autowired
    private OrderSettingDao orderSettingDao;
    @Autowired
    private OrderDao orderDao;
    @Autowired
    private SetMealDao setMealDao;


    /**
     * 任务10-手机端提交预约-添加提交预约信息
     * @return
     */
    @Override
    public Order addOrder(Order order) {
        //1.根据日期获取到预约设置orderSetting
        OrderSetting orderSetting = orderSettingDao.selectOrderSetting(order.getOrderDate());
        if (orderSetting == null) {
            //判断预约设置是否存在，不存在无法体检预约
            throw new BusinessRuntimeException(MessageConst.SELECTED_DATE_CANNOT_ORDER);
        } else if (orderSetting.getReservations() >= orderSetting.getNumber()) {
            //判断预约人数是否满了
            throw new BusinessRuntimeException(MessageConst.ORDER_FULL);
        }
        //2.用户是否重复预约（同一个用户在同一天预约了同一个套餐），根据会员ID、预约日期、套餐ID进行查询，看是否有预约记录
        long count = orderDao.countByMemberAndDateAndSetMeal(order.getMemberId(), order.getOrderDate(), order.getSetmealId());
        if (count > 0) {
            throw new BusinessRuntimeException(MessageConst.HAS_ORDERED);
        }
        //没有重复则添加预约信息
        orderDao.insertOrder(order);
        //3.预约成功，更新当天的已预约的人数orderSetting
        orderSettingDao.updateOrderSetting(orderSetting.getId(), orderSetting.getReservations() + 1);
        //返回查询到的新的预约信息
        return orderDao.selectById(order.getId());
    }
    //查出预约日期和预约类型
    @Override
    public OrderDto getOrderData(Integer id) {
        OrderDto orderDto = orderDao.getOrderData(id);
        return orderDto;
    }

    @Override
    public List<Map<String, Object>> findSetmealCount() {
        return setMealDao.findSetmealCount();
    }
}
